package com.xxlie.auth.endpoint;

import com.xxlie.auth.common.UserLoginContext;
import com.xxlie.auth.domain.Role;
import com.xxlie.auth.domain.User;
import com.xxlie.auth.interceptor.OperationLog;
import com.xxlie.auth.model.CheckLoginModel;
import com.xxlie.auth.security.auth.ajax.RoleTypeEnum;
import com.xxlie.auth.service.RoleService;
import com.xxlie.auth.service.UserService;
import com.xxlie.core.common.StringUtils;
import com.xxlie.core.common.ValidateUtil;
import com.xxlie.core.model.Page;
import com.xxlie.core.model.Query;
import com.xxlie.core.model.View;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author xxlie.com
 * @since 2017/7/30
 */
@RestController
@RequestMapping(value = "/api/sys/user")
public class UserEndpoint {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PasswordEncoder encoder;

    /**
     * 获取用户信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/findOne/{id}")
    public User findOne(@PathVariable("id") Long id) {
        if (id != null) {
            return userService.findOne(id);
        } else {
            return new User();
        }
    }

    /**
     * 用户列表
     *
     * @param query
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "list")
    public View<Page<User>> list(@RequestBody Query<User> query, HttpServletRequest request, HttpServletResponse response) {
        User user = query.getData();

        View<Page<User>> view = View.ofOk();

        Page<User> page = userService.findAll(new Page<User>(query.getPage(), query.getSize()), user);

        view.setData(page);
        return view;
    }

    /**
     * 保存用户
     *
     * @param user
     * @param request
     * @param response
     * @param result
     * @return
     */
    @OperationLog
    @RequestMapping(value = "/save")
    public View<User> save(@Validated @RequestBody User user, HttpServletRequest request, HttpServletResponse response, BindingResult result) {

        //表单校验
        if (result.hasErrors()) {
            return View.ofError(ValidateUtil.first(result.getAllErrors()));
        }

        if (user.getId() == null) {
            boolean exist = userService.getByUsername(user.getUsername()).isPresent();
            if (exist) {
                return View.ofError("用户登录名已经存在");
            }
        }

        if (user.getRole() == null) {
            Role role = roleService.findPositionByEnName(RoleTypeEnum.GENERAL.getCode());
            user.setRole(role);
        }

        if (StringUtils.isNoneBlank(user.getPassword())) {
            user.setPassword(encoder.encode(user.getPassword()));
        }
        userService.save(user);
        View<User> userView = View.ofOk();
        userView.setData(user);
        return userView;

    }

    /**
     * 删除用户
     *
     * @param id
     * @param request
     * @param response
     * @return
     */
    @OperationLog
    @RequestMapping(value = "delete/{id}")
    public View<String> deleteOne(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) {

        if (UserLoginContext.getCurrentUser().getId().equals(id)) {
            return View.ofError("删除用户失败, 不允许删除当前用户");
        } else {
            userService.delete(id);
            return View.ofOk("删除用户成功");
        }

    }

    /**
     * 批量删除用户
     *
     * @param query
     * @param request
     * @param response
     * @return
     */
    @OperationLog
    @RequestMapping(value = "batchDelete")
    public View<String> batchDelete(@RequestBody Query<Long[]> query, HttpServletRequest request, HttpServletResponse response) {

        if (query.getData() == null) {
            return View.ofError("参数为空");
        }

        List<Long> ids = new ArrayList<>();
        for (Long id : query.getData()) {
            if (null != id) {
                if (UserLoginContext.getCurrentUser().getId().equals(id)) {
                    ids.add(id);
                } else {
                    userService.delete(id);
                }
            }
        }
        if (ids.isEmpty()) {
            return View.ofError("删除用户失败, 不允许删除当前用户");
        }
        return View.ofOk("删除用户成功");
    }

    /**
     * 检查登录名
     *
     * @param loginModel
     * @return
     */
    @RequestMapping(value = "checkLoginName")
    public String checkLoginName(@RequestBody CheckLoginModel loginModel) {
        if (loginModel.getLoginName() != null && loginModel.getLoginName().equals(loginModel.getOldLoginName())) {
            return "true";
        } else if (loginModel.getLoginName() != null && !userService.getByUsername(loginModel.getLoginName()).isPresent()) {
            return "true";
        }
        return "false";
    }

}
